package edu.berkeley.guir.webquilt.proxy;

import java.io.*;
import java.util.*;
import java.net.URLEncoder;
import com.arthurdo.parser.*;
import edu.berkeley.guir.webquilt.*;
import javax.servlet.http.HttpServletResponse;

/**
 * WebQuilt class to edit HTML to redirect links, etc through the proxy.
 *
 * <P>
 * This software is distributed under the
 * <A HREF="http://guir.cs.berkeley.edu/projects/COPYRIGHT.txt">
 * Berkeley Software License</A>.
 *
 * <PRE>
 * Revisions:  - WebQuilt-v1.0-1.0.0, Feb 01 2001, jheer
 *               Created interface
 *             - WebQuilt-v1.0-2.0.0, Mar 10 2001, jheer
 *               Updated for new frame handling, deployment level proxying,
 *               and use of WebQuiltLogEntry wrapper.
 *             - WebQuilt-v2.0.0-2.0.1, Jan 14 2002, kaow
 *               Converted into abstract class and pulled methods from HTMLProxyEdit.
 * </PRE>
 *
 * This class utilizes the HtmlStreamTokenizer package from Arthur Do Consulting.<BR>
 *
 * @author  Jeffrey Heer (
 *          <A HREF="mailto:jheer@hkn.eecs.berkeley.edu">jheer@hkn.eecs.berkeley.edu</A>
 *          )
 * @author  Wayne Kao (
 *          <A HREF="mailto:kaow@cs.berkeley.edu">kaow@cs.berkeley.edu</A>
 *          )
 * @since   JDK 1.3
 * @version WebQuilt-v2.0.0-2.0.1, Jan 14 2002
 *
 */
abstract class ProxyEdit implements WebQuiltConstants {

    public static final int DEPLOY_MODE = 0;
    public static final int DEBUG_MODE  = 1;

    // ProxyEdit internal variables
    boolean   debug, headFlag;
    Hashtable editors;
    HtmlTag tagBase;

    String   strSvrUrl;   String   strSSvrUrl;
    String   strSvrBase;  String   strSSvrBase;

    // Package variables - available to TagEditors
    WebQuiltLogEntry entry = null;

    HttpServletResponse response;
    Hashtable targets;


    /**
     * ProxyEdit constructor.
     * @param strSvr the insecure server + URI of the proxy
     * @param strSSvr the secure server + URI of the proxy
     */
    public ProxyEdit(String server, String secureServer) {
	this.strSvrUrl   = server       + PROXY_FILE;
	this.strSSvrUrl  = secureServer + PROXY_FILE;
	this.strSvrBase  = server;
	this.strSSvrBase = secureServer;

	debug    = false;
	headFlag = false;
	editors  = new Hashtable();
	targets  = new Hashtable();
    }


    /**
     * Sets the debug flag. If debug is true, links will
     *  be inserted for viewing the logs while surfing
     *  and for submitting bug reports
     * @param debug the desired debugging flag value
     */
    public void setMode(int mode) {
	if ( mode == DEBUG_MODE ) { debug = true; }
    }

    /**
     * Toggles 'sync' debugging option. This method does
     *  nothing if this.debug = false.
     * @param sync the set sync value
     */
    public abstract void setSync(boolean sync);


    /**
     * Initialize proxy variables
     * @param entry the WebQuiltLogEntry data wrapper for the proxied page
     * @param response the servlet response object
     */
    public void init(WebQuiltLogEntry entry, HttpServletResponse response) {
	this.entry    = entry;
	this.response = response;
	headFlag = false;

	for ( Iterator iter = editors.values().iterator(); iter.hasNext(); ) {
	    TagEditor edit = (TagEditor)iter.next();
	    edit.init();
	}
    }


    /**
     * Registers a TagEditor with this ProxyEdit instance.
     * @param editor the TagEditor to register
     * @param tagName the name of the tag the editor processes
     */
    public void registerEditor(TagEditor editor, String tagName) {
	if ( tagName == null || editor == null ) { return; }
	editor.register(this);
	editors.put(tagName, editor);
    } //


    /**
     * Takes an HTML input stream and edits the document so that links are
     *  redirected to the proxy server. It outputs the edited HTML
     *  to the specified output stream.
     * @param istream the HTML input stream
     * @param ostream the output stream to client
     */
    public abstract void proxyCode(InputStream istream, OutputStream ostream);



    /**
     * Generate encoded URL using the parameters as in the parameters in the URL
     * @param strUrl URL to replace which will appear as a parameter
     * @param tid
     * @param linkid
     * @param inSecure default security setting
     * @return an encoded string
     */
    public String encodedUrl(String strUrl, int tid, int linkid, boolean inSecure) {

	boolean secure = inSecure;

	if ( strUrl.startsWith("https://") ) {
	    secure = true;
	} else if ( WebQuiltLib.startsWithProtocol(strUrl) ) {
	    secure = false;
	}

	//try {
		strUrl = URLEncoder.encode(strUrl);/*, urlCharEncoding);
	} catch (UnsupportedEncodingException e) {
		System.err.println("Cannot encode in " + urlCharEncoding);
		return strUrl;
	}*/


	strUrl = ( secure ? strSSvrUrl : strSvrUrl ) +
	    "?" + PARAM_REPLACE + "=" + strUrl        +
	    "&" + PARAM_TID     + "=" + tid +
	    "&" + PARAM_LINKID  + "=" + linkid;

	strUrl = response.encodeURL(strUrl);

	// replace & with &amp; to please WAP phones
	String ampedStrUrl = "";
	char thisChar;
	for (int i = 0; i < strUrl.length(); i++) {
		thisChar = strUrl.charAt(i);
		if (thisChar == '&')
			ampedStrUrl += "&#38;";
		else
			ampedStrUrl += thisChar;
	}

	return ampedStrUrl;
    }

} // of class
//==============================================================================

/*
Copyright (c) 2001 Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:

      This product includes software developed by the Group for User
      Interface Research at the University of California at Berkeley.

4. The name of the University may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
